<template>
  <div class="score-list">
    <el-card shadow="hover">
      <div class="header">
        <h2>学生成绩</h2>
        <div>
          <el-button type="primary" @click="handleExport">导出 Excel</el-button>
        </div>
      </div>

      <el-table :data="scoreList" border stripe style="width: 100%">
        <el-table-column prop="studentName" label="学生姓名" align="center" />
        <el-table-column prop="paperName" label="试卷名称" align="center" />
        <el-table-column prop="totalScore" label="总分" align="center">
          <template #default="{ row }">
            {{ row.totalScore ?? "未评分" }}
          </template>
        </el-table-column>
        <el-table-column prop="overallComment" label="评语" align="center">
          <template #default="{ row }">
            {{ row.overallComment ?? "暂无评语" }}
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="150">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleSend(row.studentName, row.paperName)"
            >
              发送预警
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { getStudentScores, sendLowScoreWarning } from "../api/answer";

import { exportScoresExcel } from "../api/answer"; // 路径根据你的文件调整

const router = useRouter();
const scoreList = ref([]);

onMounted(async () => {
  await loadScores();
});

async function loadScores() {
  try {
    const res = await getStudentScores();
    scoreList.value = res.data || [];
  } catch (err) {
    console.error("获取成绩失败:", err);
    ElMessage.error("获取成绩失败");
  }
}

async function handleSend(studentName, paperName) {
  try {
    await sendLowScoreWarning({ studentName, paperName });
    ElMessage.success(`已向 ${studentName} 发送低分预警（试卷：${paperName}）`);
  } catch (err) {
    console.error("发送低分预警失败:", err);
    ElMessage.error("发送失败");
  }
}

// 导出 Excel
async function handleExport() {
  try {
    const res = await exportScoresExcel();

    const url = window.URL.createObjectURL(res);
    const link = document.createElement("a");
    link.href = url;
    link.download = "学生成绩.xlsx";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    window.URL.revokeObjectURL(url);
    ElMessage.success("导出成功");
  } catch (err) {
    console.error("导出失败:", err);
    ElMessage.error("导出失败");
  }
}
</script>

<style scoped>
.score-list {
  padding: 20px;
}
.header {
  display: flex;
  justify-content: space-between; /* 左右两端对齐 */
  align-items: center; /* 垂直居中 */
  margin-bottom: 16px;
}
</style>
